import React, { useEffect, useState } from 'react';
import {
  Box,
  Typography,
  Grid,
  Container,
  Breadcrumbs,
  Link,
  CircularProgress,
} from '@mui/material';
import { useParams, Link as RouterLink } from 'react-router-dom';
import { Implementation, Category } from '../types';
import { api } from '../services/api';
import ImplementationCard from '../components/CodeImplementation/ImplementationCard';

const CategoryPage: React.FC = () => {
  const { categoryId } = useParams<{ categoryId: string }>();
  const [implementations, setImplementations] = useState<Implementation[]>([]);
  const [category, setCategory] = useState<Category | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadCategoryData = async () => {
      if (!categoryId) return;

      setLoading(true);
      try {
        // 加载分类信息
        const categories = await api.getCategories();
        const currentCategory = categories.find(cat => cat.id === categoryId) ||
          categories.flatMap(cat => cat.subCategories || []).find(subCat => subCat.id === categoryId);
        
        if (currentCategory) {
          setCategory(currentCategory);
        }

        // 加载该分类下的实现
        const categoryImplementations = await api.getCategoryImplementations(categoryId);
        setImplementations(categoryImplementations);
      } catch (error) {
        console.error('Error loading category data:', error);
      } finally {
        setLoading(false);
      }
    };

    loadCategoryData();
  }, [categoryId]);

  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', minHeight: '60vh' }}>
        <CircularProgress />
      </Box>
    );
  }

  if (!category) {
    return (
      <Container>
        <Typography variant="h5" color="error">
          分类不存在
        </Typography>
      </Container>
    );
  }

  return (
    <Container>
      {/* 面包屑导航 */}
      <Breadcrumbs sx={{ my: 2 }}>
        <Link component={RouterLink} to="/" color="inherit">
          首页
        </Link>
        {category.parentId && (
          <Link component={RouterLink} to={`/category/${category.parentId}`} color="inherit">
            {category.parentId}
          </Link>
        )}
        <Typography color="text.primary">{category.name}</Typography>
      </Breadcrumbs>

      {/* 分类信息 */}
      <Box sx={{ my: 4 }}>
        <Typography variant="h4" gutterBottom>
          {category.name}
        </Typography>
        <Typography variant="body1" color="text.secondary" paragraph>
          {category.description}
        </Typography>
      </Box>

      {/* 实现列表 */}
      <Grid container spacing={3}>
        {implementations.map((implementation) => (
          <Grid item xs={12} sm={6} md={4} key={implementation.id}>
            <ImplementationCard implementation={implementation} />
          </Grid>
        ))}
        {implementations.length === 0 && (
          <Grid item xs={12}>
            <Typography variant="body1" color="text.secondary" align="center">
              该分类下暂无实现
            </Typography>
          </Grid>
        )}
      </Grid>
    </Container>
  );
};

export default CategoryPage;
